package com.wlw.equipment.web;

import com.wlw.equipment.constants.MqConstants;
import com.wlw.equipment.pojo.Equipment;
import com.wlw.equipment.pojo.PageResult;
import com.wlw.equipment.service.IEquipmentService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;

@RestController
@RequestMapping("/equipment")
public class EquipmentController {

    @Autowired
    private IEquipmentService equipmentService;

    /**
     * 注入RabbitTemplate
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public PageResult equipmentList(
//            获取URL的数据! 页和每页条数! 定义变量接受！
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "1") Integer size
    ) {
//        分页数据的结果集，调用MyBatisPlus提供的方法啊page，在page中传入一个page对象，当前页和条数传入进去！就能得到这个结果集！
        Page<Equipment> result = equipmentService.page(new Page<>(page, size));
//         把总条数和全部设备数据封装进PR！
        return new PageResult(result.getTotal(), result.getRecords());
    }

    @PostMapping
    public void saveEquipment(@RequestBody Equipment equipment) {
        boolean save = equipmentService.save(equipment);

        if (save) {
            //将新增的设备ID传入MQ
            rabbitTemplate.convertAndSend(
                    MqConstants.EQUIPMENT_EXCHANGE, //指定交换机
                    MqConstants.EQUIPMENT_INSERT_KEY,   //指定RoutingKey
                    equipment.getId()); //修改的设备ID
        }
    }

    @PutMapping()
    public void updateById(@RequestBody Equipment equipment) {
        if (equipment.getId() == null) {
            throw new InvalidParameterException("id不能为空");
        }

        boolean update = equipmentService.updateById(equipment);
        if (update) {
            //将修改的设备ID传入MQ
            rabbitTemplate.convertAndSend(
                    MqConstants.EQUIPMENT_EXCHANGE, //指定交换机
                    MqConstants.EQUIPMENT_INSERT_KEY,   //指定RoutingKey
                    equipment.getId()); //修改的设备ID
        }

    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id) {
        boolean remove = equipmentService.removeById(id);
        if (remove) {
            //将删除的设备ID传入MQ
            rabbitTemplate.convertAndSend(
                    MqConstants.EQUIPMENT_EXCHANGE, //指定交换机
                    MqConstants.EQUIPMENT_DELETE_KEY,   //指定RoutingKey
                    id);    //删除的设备ID
        }
    }

    @GetMapping("/{id}")
    public Equipment queryById(@PathVariable("id") Long id) {
        return equipmentService.getById(id);
    }
}
